<template>
  <div class="manager-container">
    <el-collapse v-model="activeName">
      <el-collapse-item title="商品分类展示" name="1">
        <el-table class="category-table" stripe :data="categoryList" border style="width: 100%;height:450px">
          <el-table-column prop="sort" label="序列"/>

          <el-table-column prop="id" label="ID"/>
          <el-table-column prop="name" label="Name">
            <template #default="scope">
              <el-input type="text" clearable v-model="scope.row.name" v-show="scope.row.active"/>
              <span v-show="!scope.row.active">{{ scope.row.name }}</span>
            </template>
          </el-table-column>
          <el-table-column label="操作">
            <template #default="scope">
              <el-button size="small" type="primary" @click="categoryUpdate(scope.row)"> 修改</el-button>
              <el-button size="small" type="danger" @click="categoryDelete(scope.row)"> 删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-collapse-item>
      <el-collapse-item title="商品分类添加" name="2">
        <el-input class="box-card-input" size="large" v-model="category" placeholder="请输入商品分类,回车可快速添加。" @keyup.enter="categoryAdd" clearable/>
        <br>
        <el-button size="large" class="box-card-button" :disabled="isDisabled" @click="categoryAdd">确认添加</el-button>
      </el-collapse-item>
    </el-collapse>
  </div>
</template>

<script setup>
import {inject, onMounted, ref} from "vue";
import {invoke} from '@tauri-apps/api'
import {createId, showCustomMessage, showMessage} from '@/util/index.js'
import Sortable from 'sortablejs' ;



// 1.1 从父组件中拿到 tb_categories 里面的数据
let categories = inject("categories") ;
// 1.2 从app父组件中拿到 get_category_all 方法
let get_category_all = inject("get_category_all") ;

// 1.3.1 页面展示内容因需要自定义, 固重新定义 categories 集合
let categoryList = ref([])

// 1.3.2 因需要添加 active 属性 , 需要 重新获取一遍 categories
/**
 * 搜索 category 表
 */
const get_categories = () => {
  categoryList.value = []
  get_category_all().then(res => {
    categoryList.value = JSON.parse(res);
    // 共享组件的数据清空并重新赋值
    categories.value = [] ;
    categoryList.value.forEach(c => {
      categories.value.push({label: c.name, value: c.id})
      // 添加可访问的属性 disable 为 true , 不可访问
      c.active = false;
    })
  })
}




const drag = () => {
  const el = document.querySelectorAll('.category-table .el-scrollbar__view > table > tbody')[0];
  Sortable.create(el, {
    disabled: false,
    ghostClass: 'sortable-ghost',
    setData: function (dataTransfer) {
      dataTransfer.setData('Text', '');
    },
    onEnd: (evt) => {
      if (evt.oldIndex !== evt.newIndex) {
        const oldIndex = evt.oldIndex + 1;
        const newIndex = evt.newIndex + 1;
        let category_list = new Array();
        // 需要商品分类的 id  , 需要改的值 sort
        if (oldIndex > newIndex) {
          categoryList.value.forEach((cate, index) => {
            if (cate.sort >= newIndex && cate.sort <= oldIndex) {
              if (index + 1 === oldIndex) {
                category_list.push({id: cate.id, sort: newIndex.toString(), name: cate.name})
              } else {
                category_list.push({id: cate.id, sort: (index + 2).toString(), name: cate.name})
              }
            }
          })
        } else{
          categoryList.value.forEach((cate, index) => {
            if (cate.sort >= oldIndex && cate.sort <= newIndex) {
              if (index + 1 == oldIndex){
                category_list.push({id: cate.id, sort: newIndex.toString(), name: cate.name})
              }else{
                category_list.push({id: cate.id, sort: index.toString(), name: cate.name})
              }
            }

          })
        }
        invoke('category_update_sort', {categorylist:category_list}).then(res => {
          showMessage(res)
          get_categories();
        });
      }
    }
  });
};
let activeName = ref("1")

let category = ref();
let isDisabled = ref(false)


/**
 * 删除 category 表数据
 * @param row 要删除的 category 表 行
 */
const categoryDelete = (row) => {
  invoke("category_delete", {id: row.id}).then(res => {
    showMessage(res)
    get_categories();
  })
}

/**
 * 更新 category 表数据
 * @param row 需要更新的数据行
 */
const categoryUpdate = (row) => {
  row.active = !row.active;
  if (!row.active) {
    invoke("category_update", {category: {sort: row.sort, name: row.name, id: row.id}}).then(res => {
      showMessage(res)
      get_categories();
    })
  }
}

/**
 * 创建 category 表数据
 */
const categoryAdd = () => {
  if(category.value ){
    isDisabled.value = true;
    invoke('category_insert', {
      category: {
        sort: (categoryList.value.length + 1).toString(),
        name: category.value,
        id: createId()
      }
    }).then(res => {
      showMessage(res)
      isDisabled.value = false;
    }, err => {
      console.log("err : " + err);
    })
    category.value = "";
    get_categories();
  }else{
    showCustomMessage("请输入分类名称后再添加","error")
  }
}




onMounted(() => {
  get_categories();
  drag();
})
</script>

<style scoped lang="scss">
.manager-container {
  position: absolute;
  width: 100%;
  height: 100%;

  .box-card-input {
    width: 50%;
    margin: 0 25%;
  }

  .box-card-button {
    width: 20%;
    margin: 2% 0 0 40%;

  }
}

:deep(.el-collapse-item__header) {

}

:deep(.el-collapse-item__wrap) {
  padding: 10px 0 0 0;
}
</style>